class Solution {
public:
    /**
     * @param nums: A list of integers.
     * @param k: An integer
     * @return: The maximum number inside the window at each moving.
     */
    vector<int> maxSlidingWindow(vector<int> &nums, int k) {
        // priority_queue<int> q;
        // vector<int> res;
        // for (int i = 0; i < nums.size(); ++i) {
        //     q.push(nums[i]);
        //     if (q.size() < k) continue;
        //     else if (q.size() > k) q.pop(); //不能用堆做，pop的时候把最大的pop掉了
        //     res.push_back(q.top());
        // }
        // return res;

        deque<int> q; //维护一个单调队列
        vector<int> res;
        if (nums.empty() || nums.size() < k) return res;
        for (int i = 0; i < nums.size(); ++i) {
            while (!q.empty() && nums[i] > nums[q.front()]) {
                q.pop_front();
            }
            q.push_front(i);
            if (!q.empty() && q.back() < i - k + 1) {
                q.pop_back();
            }
            if (i >= k - 1) res.push_back(nums[q.back()]);
        }
        return res;
    }
};